package sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-15
 * Time: 15:30
 */
public class ShellSort {
    public static void main(String[] args) {
        int[] arr = {2, 1, 32, 1, 32, 1, 32, 1, 3};
        shellSort(arr);
        System.out.println(Arrays.toString(arr));
    }
    /**
     * 对insertSort的改进，将数组先趋于有序
     * @param arr
     */
    public static void shellSort(int[] arr) {
        //步长采用/2的形式（也可改为其他）
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            for (int j = gap; j < arr.length; j++) {
                int insertVal = arr[j];
                int insertIndex = j - gap;
                while (insertIndex >= 0 && insertVal < arr[insertIndex]) {
                    arr[insertIndex + gap] = arr[insertIndex];
                    insertIndex -= gap;
                }
                arr[insertIndex + gap] = insertVal;
            }
        }
    }
}
